﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Xml;

namespace WinFormAutoUpdateDemo
{
    public partial class Form1 : Form
    {
        string gLocalPath = "";
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 开始下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                button1.Enabled = false;
                button2.Enabled = false;
                bool ret = UpdateApp();
                if (ret)
                {
                    label2.Text = "下载完成";
                    MessageBox.Show("更新成功");
                    System.Diagnostics.Process.Start("regsvr.bat");
                }
                else
                {
                    button1.Text = "重新下载";
                    button1.Enabled = true;
                    MessageBox.Show("更新失败");
                }
                button2.Enabled = true;
                //hh.HttpDownload(url, path);
            }
            catch (Exception ex)
            {
                label1.Text = ex.Message;
            }
        }

        /// <summary>
        /// http下载文件
        /// </summary>
        /// <param name="url">下载文件地址</param>
        /// <param name="path">文件存放地址，包含文件名</param>
        /// <returns></returns>
        public bool HttpDownload(string url, string path)
        {
            string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp";
            System.IO.Directory.CreateDirectory(tempPath);  //创建临时文件目录
            string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path); //临时文件
            label2.Text= "正在下载的文件:"+ System.IO.Path.GetFileName(path);
            if (System.IO.File.Exists(tempFile))
            {
                System.IO.File.Delete(tempFile);    //存在则删除
            }
            try
            {
                float percent = 0;
                FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                long totalBytes = response.ContentLength;
                progressBar1.Maximum = (int)totalBytes;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                
                //创建本地文件写入流
                //Stream stream = new FileStream(tempFile, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                long totalDownloadedByte = 0;
                while (size > 0)
                {
                    totalDownloadedByte = size + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    //stream.Write(bArr, 0, size);
                    fs.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                    progressBar1.Value = (int)totalDownloadedByte;
                    percent = (int)((float)totalDownloadedByte / (float)totalBytes * 100);
                    label1.Text = "下载进度:" + percent.ToString() + "%";
                    System.Windows.Forms.Application.DoEvents();
                }
                //stream.Close();
                fs.Close();
                responseStream.Close();
                //System.IO.File.Move(tempFile, path);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        public bool UpdateApp()
        {
            bool result = false;
            try
            {
                HttpHelper hh = new HttpHelper();
                gLocalPath = hh.LocalPath;
                Dictionary<string, string> updateDic = hh.CompareLocalAndRemoteFiles();
                label3.Text = "更新文件数:0/" + updateDic.Count;
                bool success = true;
                var i = 1;
                foreach (var item in updateDic)
                {
                    label3.Text = "更新文件数:" + i.ToString() + "/" + updateDic.Count;
                    bool ret = HttpDownload(item.Key, item.Value);
                    if (!ret)
                    {
                        success = false;
                        break;
                    }
                    i++;
                }

                if (success)
                {
                    result = hh.MoveToTarget();
                    hh.UpdateLocalPath(gLocalPath);
                }
            }
            catch (Exception ex)
            {
                string str = ex.Message;
                result = false;
            }

            return result;
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        /// <summary>
        /// 更新说明
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            XmlDocument xmlLocal = new XmlDocument();
            xmlLocal.Load("updatelist.xml");
            XmlElement application = (XmlElement)xmlLocal.SelectSingleNode("application");
            string aboutUrl = application.GetAttribute("abouturl");
            System.Diagnostics.Process.Start(aboutUrl);
        }
    }
}
